import { useState } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  Typography, 
  Alert, 
  Space, 
  Divider, 
  Checkbox 
} from 'antd';
import { 
  UserOutlined, 
  LockOutlined, 
  EyeOutlined, 
  EyeInvisibleOutlined,
  GithubOutlined,
  MailOutlined
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types'; // 引入 PropTypes

const { Title, Text } = Typography;

const LoginPage = ({ onLogin }) => {
  // 表单实例
  const [form] = Form.useForm();
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [showPassword, setShowPassword] = useState(false);

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      // 清空之前的错误
      setError('');
      // 显示加载状态
      setLoading(true);

      // 模拟登录请求（实际项目中替换为真实接口调用）
      const mockLogin = (username, password) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            // 简单验证：用户名密码不为空即可（实际项目需对接后端）
            if (username && password) {
              resolve({ success: true, token: 'mock-token-123456' });
            } else {
              resolve({ success: false, message: '用户名和密码不能为空' });
            }
          }, 800);
        });
      };

      // 调用登录接口
      const result = await mockLogin(values.username, values.password);
      
      if (result.success) {
        // 登录成功，调用父组件传入的回调函数
        onLogin(result.token);
      } else {
        // 登录失败，显示错误信息
        setError(result.message || '登录失败，请检查用户名和密码');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
      console.error('登录出错:', err);
    } finally {
      // 关闭加载状态
      setLoading(false);
    }
  };

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      justifyContent: 'center', 
      alignItems: 'center', 
      background: '#f0f2f5',
      padding: '24px'
    }}>
      <Card 
        title={<Title level={3} style={{ margin: 0, textAlign: 'center' }}>账户登录</Title>}
        style={{ 
          width: '100%', 
          maxWidth: 380, 
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.08)' 
        }}
      >
        {/* 错误提示 */}
        {error && (
          <Alert 
            message="登录失败" 
            description={error} 
            type="error" 
            showIcon 
            style={{ marginBottom: 16 }}
            closable
            onClose={() => setError('')}
          />
        )}

        {/* 登录表单 */}
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{ username: '', password: '', remember: true }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名至少3个字符' }
            ]}
          >
            <Input 
              prefix={<UserOutlined className="site-form-item-icon" />} 
              placeholder="请输入用户名" 
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6个字符' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined className="site-form-item-icon" />}
              placeholder="请输入密码"
              visibilityToggle={{
                visible: showPassword,
                onVisibleChange: setShowPassword,
              }}
              iconRender={visible => visible ? <EyeOutlined /> : <EyeInvisibleOutlined />}
              autoComplete="current-password"
            />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked" noStyle>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Checkbox>记住我</Checkbox>
              <Link to="/forgot-password" style={{ color: '#1890ff' }}>
                忘记密码？
              </Link>
            </div>
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              size="large" 
              loading={loading}
              style={{ width: '100%' }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        {/* 其他登录方式 */}
        <Divider>其他登录方式</Divider>
        <Space style={{ display: 'flex', justifyContent: 'center', marginBottom: 16 }}>
          <Button 
            type="default" 
            icon={<GithubOutlined />} 
            size="large"
            style={{ width: 50, height: 50, borderRadius: 25, padding: 0 }}
          />
          <Button 
            type="default" 
            icon={<MailOutlined />} 
            size="large"
            style={{ width: 50, height: 50, borderRadius: 25, padding: 0 }}
          />
        </Space>

        {/* 注册引导 */}
        <div style={{ textAlign: 'center' }}>
          <Text>还没有账号？</Text>
          <Link to="/register" style={{ marginLeft: 4, color: '#1890ff' }}>
            立即注册
          </Link>
        </div>
      </Card>
    </div>
  );
};

// 定义 props 类型验证,必须在组件之后！
LoginPage.propTypes = {
  onLogin: PropTypes.func.isRequired, // onLogin 是必填的函数类型
};

export default LoginPage;